<template>
	<view class="bg-drak padding-bottom">
		<!-- 空白页 -->
		<use-empty v-if="empty" e-style="round" tip="无优惠券"></use-empty>

		<view v-else class="padding-lr" v-for="(item, index) in couponDatas" :key="index" @click="">
			
			<view class="coupon-area border-radius margin-top-sm bg-main">
				<view class="dflex-b">
					
					<view class="left pos-a h-full dflex-c dflex-flow-c">
						<view v-if="item.type === 1">
							<text class="price fs-big">{{ item.price}}</text>
						</view>
						
						<view v-if="item.type === 0">
							<text class="discount fs-big">{{ item.price *10 }}</text>
						</view>
						
						<view class="fs-sm" v-if="item.price > 1">直减{{ item.price }}元</view>
						
						<view class="fs-sm" v-else>全场通用</view>

					</view>
					
					<view class="right padding left_t flex1">
						<view class="dflex-b padding-bottom-xs">
							<view class="fwb fs">{{ item.title }}</view>
						</view>
						<view class="dflex-b ft-dark fs-xs padding-bottom">
							<view class="">有效期至 {{ item.end_time || '2028.05.20' }}</view>
						</view>
						<view class="w-full dflex-b">
							<!-- <view class="fs-xs ft-dark padding-top-xs">{{ item.remark || '详细信息' }}</view> -->
							<view class="fs-xs ft-dark padding-top-xs"></view>
							<view @tap.stop="receive(item.id)" class="dflex-b border-radius-big">
								<view class="tac padding-tb-xs padding-lr flex1 bg-base fs-xs">领取</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			
		</view>

		<!-- 上拉加载更多 -->
		<use-loadmore v-if="!empty && hasmore" :type="loadmoreType"></use-loadmore>
	</view>
</template>

<script>
	import {
		queryCouponsApi,
		createUserCouponsApi,
	} from "@/api/coupon.js";
	
	import {
		mapState
	} from 'vuex';
	
	export default {
		computed: {
			...mapState(["member"])
		},
		
		data() {
			return {
				// 加载更多状态
				loadmoreType: 'nomore', 

				// 浏览历史数据源
				couponDatas: [],
				// couponDatas: [{
				// 	"state": "已领取",
				// 	"type": "满减",
				// 	"name": "满100减9.9",
				// 	"price": 9.9,
				// 	"member_type": "所有人",
				// 	"order_amount": 100,
				// 	"per_max": 1,
				// 	"start_time": "2021-06-10 00:00",
				// 	"end_time": "2021.12.31",
				// 	"sort": 0,
				// 	"create_time": "2021-06-10 07:45:32"
				// }],
				
				//当前时间戳
				new_time: '',
				//过滤数组
				filteredArray: [],
				// 要领取的优惠券id
				coupons_id: '',
				empty: false,
				hasmore: 0,
				reqdata: {
					rows: 20,
					page: 1
				},
			};
		},
		watch: {
			couponDatas(e) {
				let empty = e.length === 0;
				if (this.empty !== empty) {
					this.empty = empty;
				}
			}
		},
		onShow() {
			this.new_time = new Date().getTime();
			console.log(this.new_time,"<===============this.new_time")
			
			const date = new Date(); // 获取当前日期时间
			const timestamp = date.getTime(); // 获取时间戳，单位是毫秒
			console.log(timestamp,"<================timestamp");
			
			this.loadData();
		},
		methods: {
			loadData() {
				
				// 获取数据
				this.getCouponsFunc();
				
				// this.$func.usemall.call('marketing/coupon/list', this.reqdata).then(res => {
				// 	if (res.code === 200) {
				// 		this.couponDatas = [...this.couponDatas, ...res.datas];
				// 		console.log(JSON.stringify(this.couponDatas),"<==========marketing_couponDatas")
				// 		if (res.datas.length >= this.reqdata.rows) {
				// 			if (this.reqdata.page == 1) this.hasmore = !0;
				// 		}
						
				// 		if(this.couponDatas.length === 0) {
				// 			this.empty = true;
				// 		}
				// 	}
				// });
				
			},
			receive(id) {
				let _this = this
				uni.showModal({
					title: '提示',
					content: '领取优惠券',
					success: function(res) {
						if (res.confirm) {
							if(_this.member.id){
								_this.createUserCouponsFunc(id);
							}else{
								_this.$api.msg("未登录，请先登录")
							}
							
							
							// _this.$func.usemall.call('marketing/coupon/receive', {
							// 	coupon_id: id
							// }).then(res => {
							// 	if (res.code === 200) {
							// 		_this.$api.msg('领取成功');
							// 		return;
							// 	}
								
							// 	_this.$api.msg(res.msg);
							// });
							
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},
			togoods(item) {
				// return;
				// this.$api.togoods({
				// 	// id: item.goods_id
				// 	id: item.id
				// });
			},
			
			//查询所有优惠券
			async getCouponsFunc(){
				this.couponDatas = [];
				this.filteredArray = [];
				const response = await queryCouponsApi().catch(() => {});
				if (response?.code === 200) {
				// 	const _data = [...this.orderList, ...(response?.data?.records ?? [])];
				
				// 筛选出符合条件的数组
				this.filteredArray = response?.data?.records?.filter(item => this.checkTime(item)) ?? [];
				this.couponDatas = [...this.couponDatas,...this.filteredArray];
				

				
				// this.couponDatas = this.couponDatas.map(item =>{
				// 	if(this.new_time < Date(item.end_time).getTime()){
				// 		return{
				// 			...item,
				// 		},
				// 	},
				// });
				console.log(this.filteredArray,"<==================filteredArray=======")
				console.log(this.couponDatas, "<=====couponDatas===========");
				// 	this.pages.total = response?.data?.total;
				} else {
					this.$api.msg(response?.msg ?? '服务器繁忙，请稍后再试');
				}
			},
			
			//检查优惠券是否已经过期
			checkTime(item){
				console.log(item,"<=============checkTime")
				if(item){
					let dateString  = item.end_time;
					let dateObj = new Date(dateString).getTime();

					return this.new_time < dateObj;
				}
			},
			
			//用户领取优惠券
			async createUserCouponsFunc(id){
				console.log(id,"<==============createUserCouponsFunc.id")
				this.coupons_id = id;
				const response = await createUserCouponsApi({
					uid: this?.member?.id ?? "",
					cid: this.coupons_id,
				}).catch(() =>{});
				if(response?.code == 200){
					this.$api.msg("领取成功")
				}else{
					this.$api.msg(response?.msg ?? "服务器繁忙请稍后再试")
				};
				
			},
			
			
			
		}
	};
</script>

<style lang="scss">
	page {
		background: $page-color-base;
	}

	.coupon-area {
		position: relative;
	
		.left {
			background-color: $base-color;
			color: #fff;
			width: 30%;
	
			.price {
				color: #fff !important;
			}
		}
		.right {
			margin-left: 30%;
		}
		.discount {
			font-weight: 580;
		}
		.discount::after {
			content: '折';
			font-size: 24rpx;
			margin-left: 6rpx;
		}
	
		.border-line {
			border-bottom: 1px dotted #ededed;
		}
	}
	
</style>
